package com.ztgf.order.api.cms;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ztgf.commodity.models.service.ICommodityInfoService;
import com.ztgf.order.models.vo.DealOrderInfoVO;
import com.ztgf.common.constant.Result;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.common.utils.ExcelExport2;
import com.ztgf.order.models.bo.*;
import com.ztgf.order.models.dto.*;
import com.ztgf.order.models.service.IDealOrderInfoService;
import com.ztgf.order.models.service.IOrderCommodityRelationService;
import com.ztgf.order.models.service.IOrderInfoService;
import com.ztgf.order.models.service.IOrderStatusService;
import com.ztgf.order.models.vo.*;
import com.ztgf.shopping.models.service.shop.IShopInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;

/**
 * 订单表控制器
 *
 * @author chenyu.wang
 * @Date 2020-06-03 15:32:26
 */

@RestController
@RequestMapping("/cms/orderInfo")
@Slf4j
@Api(value = "OrderInfoController", tags = "订单表接口")
public class OrderInfoController {

    @DubboReference
    private IOrderInfoService orderInfoService;
    @DubboReference
    private IDealOrderInfoService dealOrderInfoService;
    @DubboReference
    private IOrderStatusService orderStatusService;
    @DubboReference
    private IOrderCommodityRelationService orderCommodityRelationService;
    @DubboReference
    private ICommodityInfoService commodityInfoService;
    @DubboReference
    private IShopInfoService shopInfoService;

    @PostMapping(value = "/placeOrder")
    @ApiOperation(value = "下单", notes = "下单")
    public Result<List<Long>> placeOrder(String orderDataBOStr, HttpServletRequest httpServletRequest) {
        OrderDataBO orderDataBO = JSON.parseObject(orderDataBOStr, OrderDataBO.class);
        if (orderDataBO.getOrderShopInfoBOList().size() <= 0) {
            return new Result<>(CodeEnum.SHOP_CART_SHOP);
        }

        Long buyerShopId = orderDataBO.getBuyerShopId();
        if (null == buyerShopId) {
            return new Result<>(CodeEnum.SHOP_CART_NO_BUYER);
        }

        //自己不能购买自己的商品
        if (buyerShopId.equals(orderDataBO.getOrderShopInfoBOList().get(0).getShopId())) {
            return new Result<>(CodeEnum.SHOP_CART_NOT_MY_COMMODITY);
        }
        Result<List<Long>> result = new Result<>();
        try {
            result = orderInfoService.createOrder(orderDataBO, httpServletRequest.getHeader("sessionId"));
        } catch (Exception e) {
            log.error("代客下单错误", e);
            result.setCode(CodeEnum.FAIL.getCode());
            result.setMsg(e.getMessage());
            return result;
        }
        return result;
    }

    @PostMapping(value = "/getOrderInfoByOrderId")
    @ApiOperation(value = "返回订单信息", notes = "返回订单信息")
    public Result<List<OrderInfoVO>> getOrderInfoByOrderId(String ids) {
        if (StringUtils.isEmpty(ids)) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        List<OrderInfoVO> orderInfoVOList = orderInfoService.getOrderInfoByOrderId(ids);
        return new Result<>(orderInfoVOList);
    }

    @PostMapping(value = "/queryListPage")
    @ApiOperation(value = "订单列表", notes = "订单列表")
    public Result<Page<OrderInfoPageListVO>> queryListPage(OrderAdminListBO bo) {
        Page<OrderInfoPageListVO> page = orderInfoService.queryAdminListPage(bo);
        return new Result<>(page);
    }

    @PostMapping(value = "/queryDealOrderListPage")
    @ApiOperation(value = "交易订单列表", notes = "交易订单列表")
    public Result<Page<OrderInfoPageListVO>> queryDealOrderListPage(OrderAdminListBO bo) {
        Page<OrderInfoPageListVO> page = orderInfoService.queryDealOrderListPage(bo);
        return new Result<>(page);
    }

    @PostMapping(value = "getOrderDetailsById")
    @ApiOperation(value = "订单详情", notes = "订单详情")
    public Result<OrderDetailsVO> getOrderDetailsById(Long id) {
        if (null != id) {
            OrderDetailsVO details = orderInfoService.getOrderDetailsById(id);
            return new Result<>(details);
        } else {
            return new Result<>(CodeEnum.FAIL_100002);
        }
    }
    @GetMapping(value = "/getOrderCategory")
    @ApiOperation(value = "商品类目同步", notes = "商品类目同步")
    public Result getOrderCategory() {
            return orderInfoService.getOrderCategory();
    }

    @PostMapping(value = "/queryValetPlaceOrderList")
    @ApiOperation(value = "后台管理系统代客下单列表", notes = "后台管理系统代客下单列表")
    public Result<Page<OrderValetPlaceVO>> queryValetPlaceOrderList(OrderValetPlaceBO bo) {
        Page<OrderValetPlaceVO> page = orderInfoService.queryValetPlaceOrderList(bo);
        return new Result<>(page);
    }

    @PostMapping(value = "/queryOrderShip")
    @ApiOperation(value = "商品发票管理", notes = "商品发票管理")
    public Result<Page<OrderInfoShipVO>> queryOrderShip(OrderAdminListBO bo) {
        Page<OrderInfoShipVO> page = orderInfoService.queryOrderShip(bo);
        return new Result<>(page);
    }



    @GetMapping(value = "/batchExportOrderList/{ids}/{state}/{purchaseOrderType}")
    @ApiOperation(value = "批量导出订单", notes = "批量导出订单")
    public void batchExportOrderList(HttpServletResponse response, @PathVariable String ids, @PathVariable Integer state,@PathVariable Integer purchaseOrderType) {
        //创建一个数组用于设置表头
        String[] attributeNames = new String[]{"订单编号", "订单状态", "商品名称", "买家用户名", "卖家名称", "收货人", "收货人电话", "收货地址", "单价",
                "数量", "商品总价", "改价优惠", "批发优惠", "会员折扣优惠", "实付金额",
                "下单时间", "全款支付时间", "发货时间","首款支付时间","尾款支付时间","签收时间","佣金支付时间","佣金退款时间", "配送方式", "物流公司/送货员", "物流单号", "物流联系方式", "发票类型", "发票状态","开票信息", "发票寄送地址", "备注信息",
                "实付技术服务费", "预计技术服务费", "退款金额","询价单号","砍价报名费","砍价服务费","砍价退款服务费"};
        //查询订单
        List<ExportAdminOrderListVO> list = orderInfoService.queryExportAdminOrderList(null, ids, state,purchaseOrderType);
        ExcelExport2.export(response, list, attributeNames, "_订单");
    }
    @PostMapping(value = "/batchExportOrderList")
    @ApiOperation(value = "批量导出订单", notes = "批量导出订单")
    public void batchExportOrderListByAdmin(HttpServletResponse response,OrderAdminListBO bo) {
        //创建一个数组用于设置表头
        String[] attributeNames = new String[]{"订单编号", "订单状态", "商品名称", "买家用户名", "卖家名称", "收货人", "收货人电话", "收货地址", "单价",
                "数量", "商品总价", "改价优惠", "批发优惠", "会员折扣优惠", "优惠后金额","实付金额",
                "下单时间", "全款支付时间", "发货时间","首款支付时间","尾款支付时间","签收时间","佣金支付时间","佣金退款时间", "配送方式", "物流公司/送货员", "物流单号", "物流联系方式", "发票类型","发票状态", "开票信息", "发票寄送地址", "备注信息",
                "实付技术服务费", "预计技术服务费", "退款金额","询价单号","砍价报名费","砍价服务费","砍价退款服务费"};
        //查询订单
        List<ExportAdminOrderListVO> list = orderInfoService.queryExportAdminOrderList(bo);
        ExcelExport2.export(response, list, attributeNames, "_订单");
    }

    @ApiOperation(value = "手动添加线下订单",notes = "手动添加线下订单")
    @PostMapping(value = "/insert")
    public Result insert(DealOrderInfoBO saveBO) {
        try{
            boolean flag = dealOrderInfoService.add(saveBO);
            if (flag){
                return new Result<>();
            } else {
                return new Result<>(CodeEnum.FAIL_100007);
            }
        }catch (Exception e){
            return new Result<>(CodeEnum.FAIL_100020);
        }

    }

    @ApiOperation(value = "删除线下订单",notes = "删除线下订单")
    @ApiImplicitParam(name = "id",value = "线下订单id",required = true,paramType = "query",dataType = "Long")
    @PostMapping("/delete")
    public Result delete(@RequestParam("id") Long id){
        boolean flag = dealOrderInfoService.deleteById(id);
        if (flag){
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100009);
        }
    }

    @ApiOperation(value = "修改线下订单数据",notes = "修改线下订单数据")
    @PostMapping("/update")
    public Result update(DealOrderInfoBO saveBO){
        DealOrderInfoDTO dto = new DealOrderInfoDTO();
        BeanUtils.copyProperties(saveBO, dto);
        dto.setId(saveBO.getId());
        try{
            boolean flag = dealOrderInfoService.updateById(dto);
            if (flag){
                return new Result<>();
            } else {
                return new Result<>(CodeEnum.FAIL_100008);
            }
        }catch (Exception e){
            return new Result<>(CodeEnum.FAIL_100020);
        }
    }


    @ApiOperation(value = "查询线下订单数据",notes = "查询线下订单数据")
    @PostMapping("/queryPageList")
    public Result<Page<DealOrderInfoDTO>> queryPageList(DealOrderInfoBO bo){
        Wrapper<DealOrderInfoDTO> wrapper = new EntityWrapper<>();


        if (bo.getStartDate() != null){
            wrapper.ge("create_time", bo.getStartDate());
        }
        if (bo.getEndDate() != null){
            wrapper.le("create_time", bo.getEndDate());
        }
        if (StringUtils.isNotEmpty(bo.getCompanyName())){
            wrapper.like("company_name", bo.getCompanyName());
        }
        if (StringUtils.isNotEmpty(bo.getSellerName())){
            wrapper.like("seller_name", bo.getSellerName());
        }
        if (StringUtils.isNotEmpty(bo.getContactId())){
            wrapper.like("contact_id", bo.getContactId());
        }

        Page<DealOrderInfoDTO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        page = dealOrderInfoService.selectPage(page, wrapper);

        return new Result<>(page);
    }


    @PostMapping("/importDealOrder")
    @ApiOperation(value = "导入线下订单",notes = "导入线下订单")
    @SneakyThrows
    public Result importDealOrder(@RequestParam("file") MultipartFile file){
        if (null == file || file.isEmpty()) {
            return new Result<>(CodeEnum.FAIL_FILE_400000);
        }
        byte[] input = file.getBytes();
        boolean result = dealOrderInfoService.importDealOrder(input);
        return new Result<>(result);
    }

}
